package org.jeecg.modules.util;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.util.entity.TigerDataBackup;
import org.jeecg.modules.util.entity.TigerDataBackupTables;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author 程世玉
 * @create 2022/3/23 8:52
 * @PROJECT_NAME Second-SpringBootTest
 * @Description
 */
@Slf4j
@Component
public class DbBackupInfo {
    @Value("${jeecg.path.upload:}")
    private String path;

    @Value("${jeecg.path.dbbackup:}")
    private String dbpath;

    @Value("${spring.datasource.dynamic.datasource.master.port:}")
    private String port;

    @Value("${spring.datasource.dynamic.datasource.master.host:}")
    private String linux_ip;

    @Value("${spring.datasource.dynamic.datasource.master.username:}")
    private String dbUserName;

    @Value("${spring.datasource.dynamic.datasource.master.password:}")
    private String dbpassword;

    @Value("${spring.datasource.dynamic.datasource.master.dbName:}")
    private String dbName;

    public String getTabelNames(List<TigerDataBackupTables> tableNames){
        String tables = "";
        if(tableNames == null || tableNames.size() == 0)
            return null;
        for(int i=0;i<tableNames.size();i++){
            tables += " " + tableNames.get(i).getDbname();
        }
        return tables;
    }

    public void generateDbScripts(TigerDataBackup backup, String tableNames){
        /*判断要保存的路径是否正确*/
        File file = new File(path+dbpath);
        if (!file.exists()) {
            /*如果不存在则进行创建*/
            file.mkdirs();
        }
        StringBuilder mysqlFileName = new StringBuilder()
                .append(dbName)
                .append("_")
                .append(DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss"))
                .append(".sql");
        /*拼接cmd命令*/
        StringBuffer cmd = new StringBuffer()
                .append("mysqldump ")
                .append("--no-tablespaces ")
                .append("-h")
                .append(linux_ip)
                .append(" -P")
                .append(port)
                .append(" -u")
                .append(dbUserName)
                .append(" -p")
                .append(dbpassword)
                .append(" ")
                .append(dbName)
                .append(" ")
                .append(tableNames)
                .append(" > ")
                .append(path + dbpath + File.separator)
                .append(mysqlFileName);
        backup.setDumpCmd(String.valueOf(cmd));
        backup.setBackFile(path + dbpath + File.separator + String.valueOf(mysqlFileName));
        backup.setBackFileName(String.valueOf(mysqlFileName));
        backup.setDbName(dbName);
    }

    public void recoverScript(TigerDataBackup backup){
        /*拼接cmd命令*/
        StringBuffer cmd = new StringBuffer()
                .append("mysql ")
                .append("-h")
                .append(linux_ip)
                .append(" -P")
                .append(port)
                .append(" -u")
                .append(dbUserName)
                .append(" -p")
                .append(dbpassword)
                .append(" ")
                .append(dbName)
                .append(" < ")
                .append(backup.getBackFile());
        backup.setRecoverCmd(String.valueOf(cmd));
    }

    public void runScript(String script) throws Exception {

        String[] command = new String[0];
        /*我在这里就不区分是Linux还是Windows系统了，默认是Windows系统了*/
        command = new String[]{"/bin/sh", "-c", script};
        /*开始进行备份*/
        try {
            Runtime.getRuntime().exec(command);
            log.info("数据库备份/还原成功！！！");
        } catch (IOException e) {
            log.info("数据库备份失败！！！");
            e.printStackTrace();
        }
    }
}
